package com.zmytest.service.impl;

import com.zmytest.dto.LoginDto;
import com.zmytest.dto.LoginResponseDto;
import com.zmytest.dto.ResponseDto;
import com.zmytest.model.Account;
import com.zmytest.model.LoginRecord;
import com.zmytest.repository.AccountRepository;
import com.zmytest.repository.LoginRecordRepository;
import com.zmytest.service.LoginService;
import com.zmytest.util.Encryptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * Created on 2018/12/21.
 *
 * @author zhangmingyu
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    private final AccountRepository accountRepository;
    private final LoginRecordRepository loginRecordRepository;
    @Value("${login.expire-time}")
    private long loginExpireTime;

    public LoginServiceImpl(AccountRepository accountRepository, LoginRecordRepository loginRecordRepository) {
        this.accountRepository = accountRepository;
        this.loginRecordRepository = loginRecordRepository;
    }

    @Override
    public ResponseDto<LoginResponseDto> login(LoginDto loginDto) {
        String password = Encryptor.getSHACode(loginDto.getPassword());
        Account account = accountRepository.findByNameAndPassword(loginDto.getName(),password);
        if (ObjectUtils.isEmpty(account)) {
            return ResponseDto.fail("username or password is wrong");
        }
        ResponseDto<LoginRecord> loginRecord = createLoginRecord(account);
        return ResponseDto.success(new LoginResponseDto(account,loginRecord.getData()));
    }

    @Transactional
    private synchronized ResponseDto<LoginRecord> createLoginRecord(Account account){
        List<LoginRecord> records = loginRecordRepository.findAllByEnableTrueAndAccountId(account.getId());
        records.forEach(loginRecord -> {
            loginRecord.setEnable(false);
        });
        loginRecordRepository.save(records);
        LoginRecord record = new LoginRecord(account,loginExpireTime);
        LoginRecord result = loginRecordRepository.save(record);
        return ResponseDto.success(result);
    }
}
